package com.hw.hcit.feature;

import android.app.Activity;
import android.content.Context;
import android.content.IntentSender.SendIntentException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;
import com.hw.hcit.sensor.EmSensor;

public class GravitySensorTest extends JTestItem implements OnClickListener {
    private static final String TAG = "GravitySensorTest";
    private static final int TEST_STATUS_CHANGED = 0;
    private static final int TEST_STATUS_DELAY = 2000;
    private static final int READ_SENSOR_VALUE = 1;
    private static final int READ_SENSOR_XYZ = 2;
    private static final int READ_SENSOR_DELAY = 1000;
    private static final double GRAVITY_AXIS_VALUE = 9.80665 / Math.sqrt(3.0);
    private static final double RANGE = 4;
    private Context mContext;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private TextView mAcceSensorX;
    private TextView mAcceSensorY;
    private TextView mAcceSensorZ;
    private TextView mTestStatus;
    private TextView angle, angle1, hhextView;
    private int mReadCount;
    private boolean leanPassed;
    private boolean horizontalPassed;
    private Button mButton1, mButton2, mCelebrate;
    private double Φ, ρ;
    int kk;
    private static int mRepeatCount, mHorReadCount;
    private boolean putOnSend;
    Toast gToast;
    private String opSuc,opFail;
    
    public GravitySensorTest(JCtrlCallback cb) {
        super(cb);
    }

    public GravitySensorTest() {
        super();
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.hw.hcit.conf.JTestItem#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }
    /*15-11-04 gaoshenpan fix add method calibrate begin*/
    private void calibrate() {
        mHorReadCount = 0;
        putOnSend = false;
        angle.setVisibility(View.GONE);
        kk = EmSensor.doGsensorCalibration(2);
        if(kk == 1){
        	showGToast(opSuc);
        }else{
        	showGToast(opFail);
        }
        Log.d(TAG, "result--0--->" + kk);
        mHandler.sendEmptyMessageDelayed(READ_SENSOR_XYZ, TEST_STATUS_DELAY);
    }

    private void calibrate1() {
        mHorReadCount = 0;
        mRepeatCount = 0;
        angle.setVisibility(View.GONE);
        kk = EmSensor.doGsensorCalibration(2);
        if(kk == 1){
        	showGToast(opSuc);
        }else{
        	showGToast(opFail);
        }
        Log.d(TAG, "result--1--->" + kk);
        mHandler.sendEmptyMessageDelayed(READ_SENSOR_XYZ, TEST_STATUS_DELAY);
    }
    /*15-11-04 gaoshenpan fix add method calibrate end*/
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.gravity_sensor_test,
                container, false);
        mAcceSensorX = (TextView) rootView.findViewById(R.id.acce_sensor_x);
        mAcceSensorY = (TextView) rootView.findViewById(R.id.acce_sensor_y);
        mAcceSensorZ = (TextView) rootView.findViewById(R.id.acce_sensor_z);
        mTestStatus = (TextView) rootView.findViewById(R.id.test_status);
        angle = (TextView) rootView.findViewById(R.id.angle);
        angle1 = (TextView) rootView.findViewById(R.id.angle1);
        mButton1 = (Button) rootView.findViewById(R.id.button1);
        mButton2 = (Button) rootView.findViewById(R.id.button2);
        opSuc = getString(R.string.operate_success);
        opFail =  getString(R.string.operate_fail);
        mCelebrate = (Button) rootView.findViewById(R.id.button3);
        mCelebrate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mHandler.removeMessages(READ_SENSOR_VALUE);
                mHandler.sendEmptyMessage(TEST_STATUS_CHANGED);
                calibrate1();
            }
        });
        /* 15-11-04 gaoshenpan fix add button for celebrate end */
        mButton1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (Config.CURR_PROJECT.isAuto()) {
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(23, 'P');
                    } else {
                        rewriteOneByteOfNv2499(54, 'P');
                    }
                }
                testFinish(true, 1, true);

            }
        });
        mButton2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (Config.CURR_PROJECT.isAuto()) {
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(23, 'F');
                    } else {
                        rewriteOneByteOfNv2499(54, 'F');
                    }
                }
                testFinish(false, 1, false);

            }
        });
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.d("CITAU", "onClick" + "test_idx" + RANGE);
        Log.d(TAG, TAG + "onResume");
        putOnSend = false;
        mCelebrate.setEnabled(true);
        angle1.setVisibility(View.GONE);
        angle.setVisibility(View.GONE);
        mSensorManager = (SensorManager) mContext
                .getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        Log.d(TAG, TAG + "mSensor = " + mSensor);
        Log.d(TAG, TAG + "GRAVITY_AXIS_VALUE = " + GRAVITY_AXIS_VALUE);
        boolean flag = mSensorManager.registerListener(mSensorListener,
                mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        if (mSensorListener == null) {
            Log.d(TAG, TAG + "mSensorListener==null");
        }
        Log.d(TAG, "flag----->" + flag);
        mReadCount = 0;
        leanPassed = false;
        horizontalPassed = false;
        mTestStatus.setText(R.string.acce_test_status_wait);

    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.d(TAG, TAG + "onPause");
        /* 15-10-27 gaoshenpan fix unregister mSensorListener begin */
        mSensorManager.unregisterListener(mSensorListener);
        /* 15-10-27 gaoshenpan fix unregister mSensorListener end */
        mHandler.removeMessages(READ_SENSOR_VALUE);
        mHandler.removeMessages(READ_SENSOR_XYZ);
    }

    @Override
    public boolean getResult() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public String getResultInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void startTest() {
        // TODO Auto-generated method stub

    }

    @Override
    public void stopTest() {
        // TODO Auto-generated method stub

    }

    public void refresh() {

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
            /*15-11-04 gaoshenpan fix deal handler message begin */
            case TEST_STATUS_CHANGED:
                mTestStatus.setText(R.string.acce_test_status_start);
                break;
            case READ_SENSOR_VALUE:
                Log.d(TAG, TAG + "lean--->started");
                mReadCount++;
                mTestStatus.setText(R.string.put_on_45);
                if (mReadCount == 50) {
                    mReadCount = 0;
                    mTestStatus.setText(R.string.acce_test_status_fail);
                    Log.d(TAG, TAG + "50s---->failed");
                    return;
                }
                mHandler.sendEmptyMessageDelayed(READ_SENSOR_VALUE,
                        READ_SENSOR_DELAY);
                break;
            case READ_SENSOR_XYZ:
                mHorReadCount++;
                Log.d(TAG, TAG + "TestCount = " + mHorReadCount);
                if (mHorReadCount == 10) {
                    mHorReadCount = 0;
                    mRepeatCount++;
                    Log.d(TAG, TAG + "10s---->failed" + "   mRepeatCount = "
                            + mRepeatCount);
                    if (mRepeatCount < 3) {
                        calibrate();
                    }

                    if (mRepeatCount == 3) {
                        mRepeatCount = 0;
                        Log.d(TAG, TAG + "mRepeatCount = " + mRepeatCount);
                        Log.d(TAG, TAG + "30s---->failed");
                        mTestStatus.setText(R.string.acce_test_status_fail);
                        return;
                    }

                    return;
                }
                Log.d(TAG, TAG + "redo judge hor OK");
                mHandler.sendEmptyMessageDelayed(READ_SENSOR_XYZ,
                        READ_SENSOR_DELAY);
                break;
                /*15-11-04 gaoshenpan fix deal handler message end */
            default:
                break;
            }
        }

    };

    SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent event) {
            onSensorEvent(event.values[0], event.values[1], event.values[2]);
            Log.d(TAG, "SensorEventListener----->" + "onSensorChanged");
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            Log.d(TAG, "SensorEventListener----->" + "onAccuracyChanged");
            // ignore
        }
    };

    private void onSensorEvent(double x, double y, double z) {

        mAcceSensorX.setText("x = " + (float) x);
        mAcceSensorY.setText("y = " + (float) y);
        mAcceSensorZ.setText("z = " + (float) z);
        /* 15-11-03 gaoshenpan fix add logs for xyz begin */
        Log.d(TAG, TAG + "Z = " + z + " Y = " + y + " X = " + x);
        /* 15-11-03 gaoshenpan fix add logs for xyz end */
        final double xy = Math.sqrt(x * x + y * y);
        double angleZ = Math.atan2(xy, z);
        angleZ = angleZ * 180.0 / Math.PI;

        final double xz = Math.sqrt(x * x + z * z);
        double angleY = Math.atan2(xz, y);
        angleY = angleY * 180.0 / Math.PI;

        final double yz = Math.sqrt(y * y + z * z);
        double angleX = Math.atan2(yz, x);
        angleX = angleX * 180.0 / Math.PI;

        Log.d(TAG, TAG + "angleZ = " + angleZ + " angleY = " + angleY
                + " angleX = " + angleX);
        // hhextView.setText("angleZ = " + angleZ + " angleY = " + angleY +
        // " angleX = " + angleX);
        if (angleZ > 45 - RANGE && angleZ < 45 + RANGE && angleY > 60 - RANGE
                && angleY < 60 + RANGE && angleX > 120 - RANGE
                && angleX < 120 + RANGE && mReadCount >= 2) {
            leanPassed = true;
            angle1.setVisibility(View.VISIBLE);
        }
        
        /*15-11-04 gaoshenpan fix judge horizonl OK && start leantest begin */
        if (Math.abs(9.8 - z) < 0.2 && Math.abs(y) < 0.3 && Math.abs(x) < 0.3
                && mRepeatCount < 3) {
            horizontalPassed = true;
            angle.setVisibility(View.VISIBLE);
            mHandler.removeMessages(READ_SENSOR_XYZ);
            Log.d(TAG, "horizontalPassed = true");
            if (!putOnSend) {
                Log.d(TAG, "leanPassed --->start");
                mHandler.sendEmptyMessage(READ_SENSOR_VALUE);
                putOnSend = true;
            }
        }
        if (horizontalPassed && leanPassed) {
            Log.d(TAG, "leanPassed = true");
            mButton1.setEnabled(true);
            mHandler.removeMessages(READ_SENSOR_VALUE);
            mCelebrate.setEnabled(false);
            mTestStatus.setText(R.string.acce_test_status_success);
        }
        /*15-11-04 gaoshenpan fix judge horizonl OK && start leantest end */
    }

    public void showGToast(String s) {
        gToast.makeText(mContext, s,
				Toast.LENGTH_SHORT).show();
    }


}
